package com.bluno.connection;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.annotation.TargetApi;
import android.bluetooth.BluetoothSocket;
import android.util.Log;
import android.widget.Toast;


@TargetApi(7)
public class ConnectedThread extends Thread {
	
	private final BluetoothSocket socket;
	private final InputStream inStream;
	private final OutputStream outStream;
	private ConnManager manager;
	
	public ConnectedThread(ConnManager manager, BluetoothSocket socket) {
		this.socket = socket;
		InputStream tmpIn = null;
		OutputStream tmpOut = null;
		this.manager = manager;
		
		try {
			tmpIn = socket.getInputStream();
			tmpOut = socket.getOutputStream();
		} catch (IOException e) {
			
		}
		inStream = tmpIn;
		outStream = tmpOut;
	}
	
	public void run() {

		byte[] buffer = new byte[1024];
		int bytes;
		while(true) {
			try {
				bytes = inStream.read(buffer);
				
				// send the obtained bytes to the UI Activity
				manager.getHandler().obtainMessage(ConnManager.MESSAGE_READ, bytes, -1, buffer)
                .sendToTarget();
			} catch (IOException e) {
				//connectionLost
				break;
			}
		}
	}
	
	  /**
     * Write to the connected OutStream.
     * @param buffer  The bytes to write
     */
    public void write(byte[] buffer) {
        try {
            outStream.write(buffer);
            System.out.println("Enviou "+buffer.toString());
            // Share the sent message back to the UI Activity
			manager.getHandler().obtainMessage(ConnManager.MESSAGE_WRITE, buffer.length, -1, buffer)
            .sendToTarget();
        } catch (IOException e) {
           
        }
    }

    public void cancel() {
        try {
            socket.close();
        } catch (IOException e) {
            
        }
    }
}
